/**
 * 
 */
package any.desktop.server.resource;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.desktop.FileItem;
import any.desktop.server.DesktopService;

/**
 * TODO: doc me
 * 
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 71 $
 * @version
 */
public class FileItemResource extends Resource {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(FileItemResource.class);
	private DesktopService	    desktopService;
	private FileItem	        fileItem;

	@Override
	public void acceptRepresentation(final Representation entity)
	        throws ResourceException {
		final Form form = getRequest().getResourceRef().getQueryAsForm();
		if (form.getFirst("open")!= null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("To open {}", fileItem);
			}
			try {
				Desktop.getDesktop().open(new File(fileItem.getItemURI()));
				getResponse().setStatus(Status.SUCCESS_OK);
			} catch (final IOException e) {
				if (LOG.isErrorEnabled()) {
					LOG.error("Unable to open " + fileItem, e);
				}
				getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
				        e.getMessage());
			}
		}
	}

	@Override
	public void init(final Context context, final Request request,
	        final Response response) {
		super.init(context, request, response);
		final String id = (String) request.getAttributes().get("id");
		fileItem = desktopService.getFileItem(id);
		if(LOG.isDebugEnabled()){
		    LOG.debug("To get item {}",id);
		}
		setAvailable(fileItem != null);
		setModifiable(fileItem != null);
	}

	@Override
	public Representation represent(final Variant variant)
	        throws ResourceException {
		return super.represent(variant);
	}

	public void setDesktopService(final DesktopService desktopService) {
		this.desktopService = desktopService;
	}

}
